<template>
  <div class="admin-index-page">
    <div class="content">
      <div class="header">
        <div class="left">
          <el-button type="success" @click="artAdd()">添加</el-button>
          <!-- <div class="drop">
            内容信息:
            <view class="mr-5"></view>
            <el-dropdown @command="handleClickDropDown">
              <el-button type="primary">
                <span>{{ categoryList[categoryIndex]?.catelog_name }}</span
                ><el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :command="index"
                    v-for="(item, index) in categoryList"
                    :key="index"
                    >{{ item.catelog_name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div> -->
          <!-- <div class="search ml-20">
            <div style="width: 60px">搜索</div>
            <el-input
              class="mx-5"
              v-model="articleParam.article_title"
              placeholder="请输入内容"
            ></el-input>
            <el-button type="primary" @click="fetchArticle()">搜索</el-button>
          </div> -->
        </div>
        <!-- <div class="functional">
          <el-button @click="handleClickFunctional('ADD')">添加</el-button>
        </div> -->
      </div>
      <div class="table">
        <el-table :border="true" :data="tableData" height="700">
          <el-table-column
            align="center"
            prop="article_id"
            label="ID"
            width="100"
            v-if="showList[0]"
          />
          <el-table-column
            prop="article_title"
            label="标题"
            width="180"
            align="center"
            v-if="showList[1]"
          >
            <template #default="{ $index }">
              <el-input
                type="textarea"
                v-model="tableData[$index].article_title"
                autosize
              ></el-input>
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'article_title',
                    value: tableData[$index].article_title,
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="ext_field3"
            label="标题(英文)"
            width="180"
            align="center"
            v-if="showList[2]"
          >
            <template #default="{ $index }">
              <el-input
                type="textarea"
                v-model="tableData[$index].ext_field3"
                autosize
              ></el-input>
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'ext_field3',
                    value: tableData[$index].ext_field3,
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="article_brief"
            label="正文"
            align="center"
            width="180"
            v-if="showList[3]"
          >
            <template #default="{ $index }">
              <el-input
                type="textarea"
                v-model="tableData[$index].article_brief"
                :rows="2"
                :disabled="true"
              ></el-input>
              <el-button
                class="mt-5"
                @click="
                  setArticleInfo({
                    field: 'article_brief',
                    value: tableData[$index].article_brief,
                    id: tableData[$index].article_id,
                    index: $index,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="hbn"
            label="正文(英文)"
            align="center"
            width="180"
            v-if="showList[4]"
          >
            <template #default="{ $index }">
              <el-input
                type="textarea"
                v-model="tableData[$index].hbn"
                :rows="2"
                :disabled="true"
              ></el-input>
              <el-button
                class="mt-5"
                @click="
                  setArticleInfo({
                    field: 'hbn',
                    value: tableData[$index].hbn,
                    id: tableData[$index].article_id,
                    index: $index,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="article_cover"
            label="单图"
            align="center"
            width="180"
            v-if="showList[5]"
          >
            <template #default="{ $index }">
              <el-upload
                list-type="picture-card"
                class="avatar-uploader"
                :action="domain_path"
                :show-file-list="true"
                accept="image/*"
                :file-list="tableData[$index].article_cover"
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(
                      response,
                      file,
                      fileList,
                      $index,
                      'article_cover'
                    )
                "
                :on-remove="
                  () => handleAvatarRemove('single', $index, 'article_label')
                "
                :limit="1"
                :on-exceed="handleAvatarExceed"
              >
              </el-upload>
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'article_cover',
                    value: forArrayToString(tableData[$index].article_cover),
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <!-- //article_label  rec_isdeleted-->
          <el-table-column
            prop="address"
            label="多图"
            align="center"
            width="180"
            v-if="showList[6]"
          >
            <template #default="{ $index }">
              <div style="height: 200px; overflow: auto">
                <el-upload
                  list-type="picture-card"
                  class="avatar-uploader"
                  :action="domain_path"
                  :show-file-list="true"
                  accept="image/*"
                  multiple
                  :file-list="tableData[$index].article_share"
                  :on-success="
                    (response, file, fileList) =>
                      handleAvatarSuccess(
                        response,
                        file,
                        fileList,
                        $index,
                        'article_share'
                      )
                  "
                  :on-remove="handleAvatarRemove"
                  :on-exceed="handleAvatarExceed"
                  :limit="10"
                >
                </el-upload>
              </div>
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'article_share',
                    value: forArrayToString(tableData[$index].article_share),
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>

          <el-table-column
            prop="article_label"
            label="小图"
            align="center"
            width="180"
            v-if="showList[7]"
          >
            <template #default="{ $index }">
              <el-upload
                list-type="picture-card"
                class="avatar-uploader"
                :action="domain_path"
                :show-file-list="true"
                accept="image/*"
                :file-list="tableData[$index].article_label"
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(
                      response,
                      file,
                      fileList,
                      $index,
                      'article_label'
                    )
                "
                :on-remove="
                  () => handleAvatarRemove('single', $index, 'article_label')
                "
                :limit="1"
                :on-exceed="handleAvatarExceed"
              >
              </el-upload>
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'article_label',
                    value: forArrayToString(tableData[$index].article_label),
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>

          <el-table-column
            prop="rec_isdeleted"
            label="上下架"
            align="center"
            width="180"
            v-if="showList[8]"
          >
            <template #default="{ $index }">
              <el-select
                v-model="tableData[$index].rec_isdeleted"
                placeholder="Select"
                size="large"
              >
                <el-option
                  v-for="item in salceOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- <el-input
                type="textarea"
                v-model="tableData[$index].rec_isdeleted"
                autosize
              ></el-input> -->
              <el-button
                class="mt-5"
                @click="
                  handleClickFunctionalRuning('ADD', $index, {
                    field: 'rec_isdeleted',
                    value: tableData[$index].rec_isdeleted,
                    id: tableData[$index].article_id,
                  })
                "
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="article_share_title"
            label="备注"
            align="center"
            width="180"
            v-if="showList[9]"
          >
            <!-- <template #default="{ $index }">
              <p>{{ tableData[$index].article_share_title }}</p>
            </template> -->
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="flex justify-center items-center my-5">
      <el-pagination
        :page-size="articleParam.limit"
        :pager-count="6"
        :currentPage="articleParam.page"
        @current-change="handlePage"
        :total="total"
        layout="prev, pager, next"
        :background="true"
      />
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="Tips"
    @close="handleCancelFunctionalRuning"
  >
    <Editor id="tinymce" :init="init" v-model="tinymceValue" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelFunctionalRuning">取消</el-button>
        <el-button type="primary" @click="handleConfirmFunctionalRuning">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, toRef, onMounted, computed, watch } from "vue";
import RequestCommon from "@/api/common.js";
import RequestArticle from "@/api/article.js";
// tinymce
import Editor from "@tinymce/tinymce-vue";
import tinymce from "tinymce";
import "tinymce/models/dom";
import "tinymce/themes/silver/theme"; // 引用主题文件
import "tinymce/icons/default"; // 引用图标文件
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/autosave";
import "tinymce/plugins/charmap"; // 特殊字符
import "tinymce/plugins/code"; // 查看源码
import "tinymce/plugins/codesample"; // 插入代码
import "tinymce/plugins/directionality";
import "tinymce/plugins/emoticons";
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help";
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/importcss"; //图片工具
import "tinymce/plugins/insertdatetime"; //时间插入
import "tinymce/plugins/link";
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/media"; // 插入视频插件
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/pagebreak"; //分页
import "tinymce/plugins/preview"; // 预览
import "tinymce/plugins/quickbars";
import "tinymce/plugins/save"; // 保存
import "tinymce/plugins/searchreplace"; //查询替换
import "tinymce/plugins/table"; // 插入表格插件
// import "tinymce/plugins/template"; //插入模板
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount"; // 字数统计插件
import { useRoute } from "vue-router";
const route = toRef(useRoute());
watch(
  () => route,
  (newValue, oldValue) => {
    articleParam.value.page = 1;
    fetchArticle({
      catelog_id: newValue.value.params?.id,
      page: 1,
      limit: 10,
      article_title: "",
    });
  },
  {
    // immediate:true,
    deep: true,
  }
);
const tinymceValue = ref("");
const init = {
  license_key: "gpl",
  //初始化数据
  language_url: "/tinymce/langs/zh_CN.js", // 引入语言包（该语言包在public下，注意文件名称）
  language: "zh_CN", // 这里名称根据 zh-Hans.js 里面写的名称而定
  skin_url: "/tinymce/skins/ui/oxide", // 这里引入的样式
  max_height: "100vh", // 限制高度
  plugins:
    "save quickbars preview autosave autolink anchor accordion link lists image code table wordcount", // 富文本插件
  toolbar:
    "save preview restoredraft anchor accordion bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat",
  // branding: false, // //是否禁用“Powered by TinyMCE”
  menubar: true, //顶部菜单栏显示
  images_upload_url: "http://ywapi.kfcit.com/fileupload/home",
  // // paste_convert_word_fake_lists: false, // 插入word文档需要该属性
  // content_css: "/skins/content/default/content.css", //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
  images_upload_handler: (blobInfo, success, failure, progress) => {
    return new Promise((resolve, reject) => {
      const formDataUp = new FormData();
      // img  是接口需要的上传的属性名，一般属性名是 file
      formDataUp.append("file", blobInfo.blob(), blobInfo.filename());
      RequestCommon.uploadFile(formDataUp).then((res) => {
        resolve(domain_pic + res[0].path);
      });
    });
  },
};

const domain_path = "http://ywapi.kfcit.com/fileupload/home";
const domain_pic = "http://ywapi.kfcit.com/";
const dialogVisible = ref(false);
const categoryList = ref([]);
const categoryIndex = ref(0);

const articleInfo = ref({
  field: null,
  value: null,
  id: null,
  index: null,
});
const articleParam = ref({
  catelog_id: "",
  page: 1,
  limit: 10,
  article_title: "",
});
const total = ref(0);
//  上下架
const salceOption = [
  {
    value: 0,
    label: "上架",
  },
  {
    value: 1,
    label: "下架",
  },
];
const singleData = ref([]);
const tableData = ref([]);
const showList = ref([]);
const handlePage = (pno) => {
  articleParam.value.page = pno;
  fetchArticle({ catelog_id: route.value.params.id || 1 });
};

// handle
const handleClickDropDown = async (e) => {
  categoryIndex.value = e;
  articleParam.value.catelog_id =
    categoryList.value[categoryIndex.value].catelog_id;
  fetchArticle();
  console.log("handleClickDropDown", e);
};

const handleAvatarRemove = (single, index, filed) => {
  if (single == "single") {
    tableData.value[index][filed] = [];
  }
};

const handleAvatarExceed = (e) => {
  ElMessage("超过文件上传限制");
  console.log("=======-handleAvatarExceed", e);
};

const handleAvatarSuccess = (response, file, fileList, index, fileds) => {
  let files = response[0];
  tableData.value[index][fileds].push({
    url: forSplitHttp(files.path),
    ...files,
  });
  console.log("handleAvatarSuccess", tableData.value[index][fileds]);
};
// Functional
const FetchFunctionalAdd = async (param) => {
  await RequestArticle.updated(param)
    .then(() => {
      ElMessage({
        type: "success",
        message: "操作成功",
      });
      fetchArticle({
        catelog_id: route.value.params.id || 1,
      });
    })
    .catch(() => {
      ElMessage({
        type: "error",
        message: "操作失败",
      });
    });
};
const setFiledValue = (index, field, value) => {
  tableData.value[index][field] = value;
};

const clearEditorValue = () => {
  tinymceValue.value = "";
  dialogVisible.value = false;
};
const handleCancelFunctionalRuning = () => {
  clearEditorValue();
};
const handleConfirmFunctionalRuning = () => {
  handleClickFunctionalRuning("ADD", null, {
    field: articleInfo.value.field,
    value: encodeURIComponent(tinymceValue.value),
    id: articleInfo.value.id,
  });
};
const handleClickFunctionalRuning = (type, index, param) => {
  if (!param.value) {
    return ElMessage({
      type: "warning",
      message: "值不能为空",
    });
  }
  if (tinymceValue.value) {
    setFiledValue(
      articleInfo.value.index,
      articleInfo.value.field,
      tinymceValue.value
    );
  }

  switch (type) {
    case "ADD":
      clearEditorValue();
      FetchFunctionalAdd(param);
      break;
    case "EDIT":
      break;
    default:
      break;
  }
};
const handleClickFunctional = (type) => {
  console.log("====", type);
  switch (type) {
    case "ADD":
      handleVisible(dialogVisible);
      break;
    case "EDIT":
      handleVisible(dialogVisible);
      break;
    default:
      break;
  }
};

const setArticleInfo = (param) => {
  handleVisible(dialogVisible);
  tinymceValue.value = param.value;
  articleInfo.value = {
    ...param,
  };
  console.log(
    "===============setArticleInfo",
    tinymceValue.value,
    articleInfo.value
  );
};
const handleVisible = (fileds) => {
  fileds.value = !fileds.value;
};

// component api
onMounted(() => {
  fetchInitializationData();
  tinymce.init({});
});

// 网络请求
// 请求分类
const fetchCategory = async () => {
  const { cats } = await RequestCommon.category();
  categoryList.value = cats;
  categoryList.value.unshift({ catelog_name: "全部", catelog_id: 1 });
};

const fetchArticle = async (articleParamOver) => {
  const param = {
    ...articleParam.value,
    ...articleParamOver,
  };
  console.log(param);
  let { cats, total: t, show } = await RequestArticle.article(param);
  tableData.value = cats;
  total.value = t;
  showList.value = show;
  tableData.value.map((item) => {
    let article_cover_arr = item.article_cover
      ? item.article_cover.split(",")
      : [];
    let article_share_arr = item.article_share
      ? item.article_share.split(",")
      : [];
    let article_label_arr = item.article_label
      ? item.article_label.split(",")
      : [];
    item.article_cover = article_cover_arr.map((jitem) => {
      return { url: forSplitHttp(jitem) };
    });
    item.article_share = article_share_arr.map((jitem) => {
      return { url: forSplitHttp(jitem) };
    });
    item.article_label = article_label_arr.map((jitem) => {
      return { url: forSplitHttp(jitem) };
    });
  });
};
const fetchInitializationData = () => {
  // fetchCategory();
  fetchArticle({
    catelog_id: route.value.params?.id || 1,
    page: 1,
    limit: 10,
    article_title: "",
  });
};

// computed
const forArrayToString = computed(() => {
  return (array) => {
    const tmpArry = array.length ? [...array] : [];
    return tmpArry.map((item) => item.url).join();
  };
});
const forSplitHttp = (value) => {
  return value.includes("http") ? value : domain_pic + value;
};
const artAdd = async () => {
  console.log(route.value.query.name, "route.value.query.name");
  const res = await RequestArticle.artAdd({
    cv1: route.value.params.id || 1,
    cv2: "新-" + route.value.query.name || "logo",
  });
  articleParam.value.page = 1;
  fetchArticle({
    catelog_id: route.value.params.id || 1,
    page: 1,
    limit: 10,
    article_title: "",
  });
};
</script>

<style lang="scss" scoped>
.admin-index-page {
  .content {
    .header {
      width: 100%;
      padding: 20px 0;
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;

        .drop,
        .search {
          display: flex;
          align-items: center;
        }
        .search {
          width: 350px;
        }
      }
    }
    .table {
      width: 100%;
    }
  }
}
::v-deep .el-upload-list--picture-card .el-upload-list__item,
::v-deep .el-upload--picture-card {
  height: 120px;
  width: 120px;
}
</style>
